import math
from typing import List, Tuple, TypeVar, Generic
from pydantic import BaseModel, Field
from app.schemas.account import PaginationMeta, PaginationLinks

T = TypeVar('T')


class PaginationParams:
    """分页参数处理类"""
    
    @staticmethod
    def validate_params(page: int = 1, page_size: int = 10) -> Tuple[int, int]:
        """验证和标准化分页参数"""
        # 限制分页大小，防止过大的请求
        if page_size > 100:
            page_size = 100
        if page_size < 1:
            page_size = 1
        if page < 1:
            page = 1
        return page, page_size


class PaginationResponse(BaseModel, Generic[T]):
    """通用分页响应模型"""
    data: List[T] = Field(..., description="数据列表")
    meta: dict = Field(..., description="分页元信息")
    links: PaginationLinks = Field(..., description="分页链接")


class PaginationHelper:
    """分页辅助工具类"""
    
    @staticmethod
    def build_pagination_meta(total_items: int, page: int, page_size: int) -> PaginationMeta:
        """构建分页元信息"""
        total_pages = math.ceil(total_items / page_size) if total_items > 0 else 1
        return PaginationMeta(
            total_items=total_items,
            total_pages=total_pages,
            current_page=page,
            page_size=page_size
        )
    
    @staticmethod
    def build_pagination_links(base_url: str, page: int, page_size: int, total_pages: int) -> PaginationLinks:
        """构建分页链接"""
        return PaginationLinks(
            self=f"{base_url}?page={page}&page_size={page_size}",
            first=f"{base_url}?page=1&page_size={page_size}",
            next=f"{base_url}?page={page + 1}&page_size={page_size}" if page < total_pages else None,
            last=f"{base_url}?page={total_pages}&page_size={page_size}"
        )
    
    @staticmethod
    def create_pagination_response(
        items: List[T], 
        total_items: int, 
        page: int, 
        page_size: int, 
        base_url: str
    ) -> PaginationResponse[T]:
        """创建完整的分页响应"""
        # 构建分页元信息
        pagination_meta = PaginationHelper.build_pagination_meta(total_items, page, page_size)
        
        # 构建分页链接
        links = PaginationHelper.build_pagination_links(
            base_url, page, page_size, pagination_meta.total_pages
        )
        
        return PaginationResponse(
            data=items,
            meta={"pagination": pagination_meta},
            links=links
        )